// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    ended: false,
    started: false,
    continue: true,
    result: '',
    freeCard: [],
    makers: [],
    cards: [],
    freeTotal: 0,
    makersTotal: 0,
    length: 52,
    session: 0,
    victory: 0,
    winRate: 100,
    balance: 1000,
    baseScore: 1,
    money: 0,
    disCard: {
      imageUrl: '/images/cards/back.png'
    },
    betButtons: []
  },
  // 开始发牌
  start() {
    this.initData()
    this.continue()
  },
  // 继续游戏不重新洗牌
  continue() {
    if (this.data.balance < 1) {
      const _this = this;
      wx.showModal({
        title: '警告',
        content: '账户余额不足，请充值。',
        success(res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/recharge/index?balance=' + this.data.balance,
            })
            return
          } else if (res.cancel) {
            // TODO 退出游戏
            _this.setData({ started: false, ended: false })
          }
        }
      })
    } else {
      if (this.data.length < 4) {
        this.checkCards();
      } else {
        this.getCards();
      }
    }

  },
  // 获取手牌
  getCards() {
    let cards = this.data.cards
    let freeCard = [] // 闲家牌
    freeCard.push(cards.pop(), cards.pop())
    let makers = [] // 庄家牌
    makers.push(cards.pop(), cards.pop())
    this.setData({
      baseScore: 1,
      length: this.data.cards.length,
      ended: false,
      result: '',
      started: true,
      freeCard,
      makers,
      freeTotal: this.getTotal(freeCard),
      makersTotal: this.getTotal(makers)
    })
  },
  // 检查剩余牌数量
  checkCards() {
    const _this = this;
    wx.showModal({
      title: '警告',
      content: '剩余牌数不足4，是否重新开始洗牌？',
      success(res) {
        if (res.confirm) {
          _this.initData()
          _this.getCards()
          return
        } else if (res.cancel) {
          // TODO 取消就统计信息显示
        }
      }
    })
  },
  // 添加牌
  add() {
    if (this.data.freeTotal == 21) {
      wx.showToast({
        title: '你是傻子嘛？',
        icon: 'error',
      })
    }
    if (this.data.length < 1) {
      const _this = this;
      wx.showModal({
        title: '警告',
        content: '剩余牌数不足，是否重新开始洗牌？',
        cancelText: '结束',
        success(res) {
          if (res.confirm) {
            _this.initData()
            _this.getFree()
          } else if (res.cancel) {
            _this.end()
          }
        }
      })
    } else {
      this.getFree()
    }
  },
  // 获取闲家手牌
  getFree() {
    let freeCard = this.data.freeCard // 闲家牌
    freeCard.push(this.data.cards.pop())
    this.setData({
      length: this.data.cards.length,
      freeCard,
      freeTotal: this.getTotal(freeCard),
    })
  },
  // 结束，比较庄家和闲家的点数
  end() {
    // 闲家点结束  庄家比较自己的牌，决定是否加牌 系统自动完成
    this.getMarkers();
    const freeTotal = this.data.freeTotal
    const makersTotal = this.data.makersTotal
    // 牌面小于21 并且大于庄家牌面/庄家牌面大于21
    const flag = freeTotal <= 21 && (freeTotal > makersTotal || makersTotal > 21);
    wx.showToast({
      title: flag ? '恭喜你，你赢了！' : '输只是暂时的！',
      icon: flag ? 'success' : 'error'
    })
    let balance = this.data.balance
    let freeScore = this.data.freeScore
    if (flag && freeTotal == 21) {
      // markerScore -= 2 * this.data.baseScore
      balance += 2 * this.data.baseScore
    } else if (flag) {
      // markerScore -= this.data.baseScore
      balance += this.data.baseScore
    } else {
      balance -= this.data.baseScore
      // markerScore += this.data.baseScore
    }
    this.setData({
      result: flag ? '闲家胜！' : '庄家胜！',
      ended: true,
      session: this.data.session + 1,
      victory: flag ? this.data.victory + 1 : this.data.victory,
      balance
    })
    const winRate = Math.floor((parseInt(this.data.victory) / parseInt(this.data.session)) * 100);
    this.setData({ winRate })
    console.log(this.data.winRate);
  },
  // 庄家获取牌
  getMarkers() {
    let makersTotal = this.data.makersTotal
    // 庄家能看到闲家的牌面总和
    const freeCanSeeTotal = this.getTotal(this.data.freeCard.splice(1))
    let makers = this.data.makers
    while ((makersTotal < 16 || makersTotal < freeCanSeeTotal && freeCanSeeTotal < 21) && this.data.length > 0) {
      makers.push(this.data.cards.pop())
      this.setData({ makers })
      makersTotal = this.getTotal(makers)
    }
    this.setData({
      makersTotal,
      length: this.data.cards.length,
    })
  },
  // 认输
  lose() {
    const freeTotal = this.data.freeTotal
    const makersTotal = this.data.makersTotal
    const flag = freeTotal <= 21 && freeTotal > makersTotal || makersTotal > 21
    wx.showToast({
      title: flag ? '你应该多坚持的！' : '输只是暂时的',
      icon: 'error'
    })
    this.setData({
      result: '庄家胜！',
      session: this.data.session + 1,
      ended: true,
      balance: this.data.balance - this.data.baseScore
    })
    const winRate = Math.floor((parseInt(this.data.victory) / parseInt(this.data.session)) * 100);
    this.setData({ winRate })
  },
  // 下注
  bet(e) {
    const times = e.currentTarget.dataset.times;
    if (!this.data.ended) {
      this.setData({
        baseScore: 1 * times
      })
    }
  },
  // 计算牌面总和
  getTotal(arr) {
    let total = 0;
    let codes = [];
    arr.forEach(a => codes.push(a.code > 10 ? 10 : a.code))
    for (let i = 0; i < codes.length; i++) {
      let code = parseInt(codes[i])
      if (code == 1 && total < 21) {
        total += 11;
        codes.splice(i, 1, 11);
      } else {
        total += code > 10 ? 10 : code
      }
    }
    while (total > 21 && codes.indexOf(11) > -1) {
      total = total - 10
      codes.splice(codes.indexOf(11), 1, 1)
    }
    return total
  },
  // 洗牌
  getCard() {
    let cards = [];
    for (let i = 1; i <= 13; i++) {
      cards.push({ code: i, name: '红心' + i, imageUrl: '/images/cards/' + i + 'x.png' })
      cards.push({ code: i, name: '梅花' + i, imageUrl: '/images/cards/' + i + 'h.png' })
      cards.push({ code: i, name: '黑桃' + i, imageUrl: '/images/cards/' + i + 't.png' })
      cards.push({ code: i, name: '方块' + i, imageUrl: '/images/cards/' + i + 'k.png' })
    }
    cards.sort(function () {
      return 0.5 - Math.random()
    })
    return cards;
  },
  // 充值
  recharge() {
    wx.redirectTo({
      url: '/pages/recharge/index?balance=' + this.data.balance,
    })
  },
  // 初始化玩家手牌
  initData() {
    this.setData({
      cards: this.getCard(),
      freeCard: [],
      makers: [],
      freeTotal: 0,
      makersTotal: 0,
      ended: false,
      result: '',
      markerScore: this.data.started ? this.data.markerScore : 0,
      freeScore: this.data.started ? this.data.freeScore : 0,
      session : 0,
      victory: 0,
      winRate: 100,
    })
  },
  // 初始化数据
  onShow() {
    const betButtons = [{
      color: '#4491c5',
      text: 'x10',
      times: 10
    },
    {
      color: '#ba328d',
      text: 'x20',
      times: 20
    },
    {
      color: '#74ab4d',
      text: 'x30',
      times: 50
    },
    {
      color: '#cf3835',
      text: 'x50',
      times: 100
    },]
    this.setData({ cards: this.getCard(), betButtons })
  },
  onLoad(options) {
    if (options) {
      const money = parseInt(options.money)
      this.setData({ balance: money ? money : 1000 })
    }
  }
})
